package com.wyz.saas.common.view.airpanel

import android.annotation.TargetApi
import android.app.Activity
import android.content.Context
import android.os.Build
import android.util.AttributeSet
import android.widget.FrameLayout
import com.wyz.saas.common.R
import com.wyz.saas.common.utils.yes

open class AirPanelFrameLayout : FrameLayout, AirPanel.Panel {

    private lateinit var mDelegate: AirPanel.Helper

    constructor(context: Context) : this(context, null)

    constructor(
        context: Context,
        attrs: AttributeSet?
    ) : this(context, attrs, 0)

    constructor(
        context: Context,
        attrs: AttributeSet?,
        defStyleAttr: Int
    ) : super(context, attrs, defStyleAttr) {
        init(attrs, defStyleAttr, 0)
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    constructor(
        context: Context,
        attrs: AttributeSet?,
        defStyleAttr: Int,
        defStyleRes: Int
    ) : super(context, attrs, defStyleAttr, defStyleRes) {
        init(attrs, defStyleAttr, defStyleRes)
    }

    private fun init(
        attrs: AttributeSet?,
        defStyleAttr: Int,
        defStyleRes: Int
    ) {
        val attribute = AirAttribute.obtain(
            this, attrs, defStyleAttr, defStyleRes,
            R.styleable.AirPanelLinearLayout,
            R.styleable.AirPanelLinearLayout_airPanelMinHeight,
            R.styleable.AirPanelLinearLayout_airPanelMaxHeight
        )
        mDelegate = AirPanelHelper(this, attribute)
        AirPanelUtils.log("AirPanelFrameLayout constructor %s ", attribute)
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        (!isInEditMode).yes { mDelegate.setup(context as Activity) }
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        var temp = heightMeasureSpec
        temp = mDelegate.calculateHeightMeasureSpec(temp)
        super.onMeasure(widthMeasureSpec, temp)
    }

    override fun openPanel() {
        mDelegate.openPanel()
    }

    override fun closePanel() {
        mDelegate.closePanel()
    }

    override fun isOpen(): Boolean {
        return mDelegate.isOpen()
    }

    override fun adjustPanelHeight(heightMeasureSpec: Int) {
        mDelegate.adjustPanelHeight(heightMeasureSpec)
    }

    override fun setup(panelListener: AirPanel.PanelListener) {
        mDelegate.setup(panelListener)
    }

    override fun setOnStateChangedListener(listener: AirPanel.OnStateChangedListener) {
        mDelegate.setOnStateChangedListener(listener)
    }
}